import { _decorator, Component, AudioClip, AudioSource, tween, Tween } from "cc";
const { ccclass } = _decorator

@ccclass('AudioItem')
export class AudioItem extends Component {
    /**
     * 是否正在播放
     */
    isPlay: boolean = false;
    /**
     * 开始播放的时间戳
     */
    startPlayTimmstamp: number = 0;
    /**
     * 播放音效
     */
    private _clip: AudioClip = null;


    get audioSource(): AudioSource {
        return this.getComponent(AudioSource)
    }

    /**
     * 播放音效
     * @param clip 
     * @param times 
     * @param volume 
     * @param callback 
     */
    play(clip: AudioClip, times: number, volume: number) {
        // 如果正在播放，则直接返回(防止外部调用导致资源计数错误)
        if (this.isPlay) return;

        this.isPlay = true;
        this.startPlayTimmstamp = new Date().getTime();
        this._clip = clip;

        this.audioSource.loop = false;
        this.audioSource.clip = this._clip;
        //添加引用
        this._clip.addRef();

        this.audioSource.volume = volume
        const duration = this._clip.getDuration()

        Tween.stopAllByTarget(this.node)
        tween(this.node)
            .call(() => this.audioSource.play())
            .delay(duration)
            .union()
            .repeat(times)
            .call(() => this.stop())
            .start()
    }

    /**
     * 停止音效
     */
    stop() {
        // 如果没有播放，则直接返回(防止外部调用导致资源计数错误)
        if (!this.isPlay) return;

        Tween.stopAllByTarget(this.node)
        this.audioSource.stop();
        this.audioSource.clip = null;

        this.isPlay = false
        //不释放，只减少计数
        this._clip.decRef(false);
        this._clip = null;
    }

    /**
     * 设置音效
     * @param volume 
     */
    setVolume(volume: number) {
        this.audioSource.volume = volume;
    }
}